package connection;

import java.io.DataOutputStream;
import java.io.IOException;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

public class BTConnection implements Runnable, DiscoveryListener {
	public static final String BT_PROTOCOL = "btspp";
	private Thread thread;
	private StreamConnection conn;
	private String url = "btspp://008098d41766:31";
	private DataOutputStream os;
	private CommandRelay commRelay;
	private boolean end = false;
	private DiscoveryAgent agent;
	private LocalDevice device;
	private RemoteDevice yacht;
	private String btaddress = "008098D41766";
	private final Object DEVICE_LOCK = new Object();
	private final Object SERVICE_LOCK = new Object();
	
	public BTConnection(CommandRelay commRelay) {
		this.commRelay = commRelay;
		thread = new Thread(this, "Bluetooth");
		thread.start();
	}

	public void run() {
		try {
			device = LocalDevice.getLocalDevice();
			agent =  device.getDiscoveryAgent();
			agent.startInquiry(DiscoveryAgent.GIAC, this);
		} 
		catch (BluetoothStateException bse) {
			bse.printStackTrace();
		}
	}

	public void deviceDiscovered(RemoteDevice btDev, DeviceClass btDevClass) {
		synchronized(DEVICE_LOCK) {
			if (btDev.getBluetoothAddress() == "008098D41766") {
				yacht = btDev;
			}
		}
	}

	public void inquiryCompleted(int discType) {
		switch (discType) {
			case INQUIRY_COMPLETED:
				System.out.println("Inquiry completed...");
				synchronized(DEVICE_LOCK) {
				      DEVICE_LOCK.notifyAll();
				    }
					if (yacht != null) {
						System.out.println(yacht.getBluetoothAddress());
						UUID[] sNumber = {new UUID(0x0003)}; // Filter op Serial Port services
						System.out.println(sNumber.length);
						try {
							System.out.println("Search Services...");
							agent.searchServices(null, sNumber, yacht, this);
						}
						catch (BluetoothStateException e) {
							e.printStackTrace();
						}
					}
				break;
			case INQUIRY_TERMINATED:
				System.out.println("Inquiry terminated...");
				break;
			case INQUIRY_ERROR:
				System.err.println("Inquiry error...");				
		}
	}

	public void serviceSearchCompleted(int transID, int respCode) {
		switch (respCode) {
			case SERVICE_SEARCH_COMPLETED:
				System.out.println("Service search completed...");
				break;
			case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
				System.err.println("Service search device not reachable...");
				break;
			case SERVICE_SEARCH_ERROR:
				System.err.println("Service search error...");
				break;
			case SERVICE_SEARCH_NO_RECORDS:
				System.err.println("Service search no records...");
				break;
			case SERVICE_SEARCH_TERMINATED:
				System.out.println("Service search terminated...");
				
		}
	}

	public void servicesDiscovered(int transID, ServiceRecord[] records) {
		System.out.println("Service Discovered...");
		int i = 0;
		while (i < records.length && !url.startsWith(BT_PROTOCOL)) {
			url = records[i].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
			i++;
		}
		try {
			conn = (StreamConnection)Connector.open(url);
			os = conn.openDataOutputStream();
			while(!end) {
				os.write(commRelay.getCommand());
				Thread.sleep(100);
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
		} 
		catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
